//
//  UIViewController+public extension.swift
//  AJiTai
//
//  Created by BO ZHOU on 2020/5/18.
//  Copyright © 2020 BO ZHOU. All rights reserved.
//

import UIKit

private var loadingView_key = "loadingView_key"
private var networkErrorView_key = "networkErrorView_key"
private var noDataView_key = "noDataView_key"




open class HintView: UIView {
    
    private lazy var hintLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 15)
        label.textAlignment = .center
        return label
    }()
    
    
    static private(set) var shared: HintView = {
       
        let view = HintView()
        view.backgroundColor = UIColor.orange
        
        view.addSubview(view.hintLabel)
        
        view.layer.cornerRadius = 5
        
        return view
    }()
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        self.hintLabel.frame = self.bounds
    }
    
    /** hintView高度 */
    let selfHeight: CGFloat = 44
    
    /** 在保证label宽度之外, 左右扩充的宽度 */
    let labelMargin: CGFloat = 20
    
    /** 显示之后多少秒消失 */
    let showTime: Double = 2
    
    /** 显示在屏幕上的起始高度比例 */
    let heightRadio: CGFloat = 0.75
    
    static func show(_ text: String!) {
        
        if text == nil {return}
        NSObject.cancelPreviousPerformRequests(withTarget: shared, selector: #selector(dismiss), object: nil)
        
        shared.alpha = 0
        shared.hintLabel.text = text
        
        if shared.superview == nil {
            KEY_WINDOW?.addSubview(shared)
        }
        
        let width = min(getLabelWidth(font: shared.hintLabel.font, height: shared.selfHeight, string: text).width + shared.labelMargin * 2, SCREEN_WIDTH - 20)
        
    
        
        shared.frame = CGRect(x: SCREEN_WIDTH/2 - width/2, y: SCREEN_HEIGHT*shared.heightRadio, width: width, height: shared.selfHeight)
        
        animation {
            shared.alpha = 1
            
            shared.perform(#selector(dismiss), with: nil, afterDelay: shared.showTime)
        }
    }
    
    @objc private func dismiss() {
        UIView.animate(withDuration: 0.25) {
            self.alpha = 0
        } completion: { (issuccess) in
            self.removeFromSuperview()
        }
    }
    
    
}
